#!/bin/bash

# 设置正确的语言环境
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export PYTHONIOENCODING=UTF-8

# 输出文件
OUTPUT_FILE="commit_hashes_and_times.txt"

# 旧的开始时间和结束时间
oldStartTime=$1
oldEndTime=$2

# 将 oldStartTime 和 oldEndTime 转为 Unix 时间戳
oldStartTimestamp=$(date -d "$oldStartTime" +%s)
oldEndTimestamp=$(date -d "$oldEndTime" +%s)

# 检查 git-filter-repo 是否存在
GIT_FILTER_REPO_PATH="./git_filter_repo.py"
if [ ! -f "$GIT_FILTER_REPO_PATH" ]; then
    echo "Error: git-filter-repo not found at $GIT_FILTER_REPO_PATH"
    exit 1
fi

# 清空输出文件
> "$OUTPUT_FILE"

# 通过git-filter-repo提取所有提交记录到临时文件
python "$GIT_FILTER_REPO_PATH" --commit-callback "
from datetime import datetime
import pytz

# 提取哈希值和作者日期
commit_hash = commit.original_id.decode('utf-8')  # 获取原始提交的哈希值
committer_date_bytes = commit.committer_date  # 获取作者日期的原始字节对象
committer_date_str = committer_date_bytes.decode('utf-8')  # 解码为字符串
committer_timestamp = int(committer_date_str.split(' ')[0])  # 提取 Unix 时间戳
committer_date = datetime.utcfromtimestamp(committer_timestamp)  # 转换为日期时间对象

# 获取时区（假设是 +0800 时区）
local_tz = pytz.timezone('Asia/Shanghai')  # 中国时区
committer_date_local = pytz.utc.localize(committer_date).astimezone(local_tz)  # 转换为中国时区
formatted_date = committer_date_local.strftime('%Y-%m-%d %H:%M:%S')  # 格式化为 YYYY-MM-DD HH:MM:SS

# 在这里我们将数据写入临时文件
with open('temp_commit_data.txt', 'a', encoding='utf-8') as f:
    f.write(f'{commit_hash} {committer_timestamp} {formatted_date}\n')
"

# 对临时文件中的数据按时间戳排序，并输出到最终文件
# sort -k2,2n temp_commit_data.txt | awk '{print $1, $3, $4}' > "$OUTPUT_FILE"
# sort -k2,2n temp_commit_data.txt | awk '{print $1 "," $3 " " $4}' > "$OUTPUT_FILE"
sort -k2,2n temp_commit_data.txt | \
awk -v start="$oldStartTimestamp" -v end="$oldEndTimestamp" \
    '$2 >= start && $2 <= end {print $1 "," $2 "," $3 " " $4}' > "$OUTPUT_FILE"

# 计算输出文件的行数
# line_count=$(wc -l < "$OUTPUT_FILE")
# 在输出文件最后一行追加记录数量
# echo "$line_count" >> "$OUTPUT_FILE"
# 删除临时文件
rm temp_commit_data.txt

# 检查结果
if [[ -f "$OUTPUT_FILE" && -s "$OUTPUT_FILE" ]]; then
    echo "Commit hashes and times have been successfully extracted to $OUTPUT_FILE"
else
    echo "Error: Failed to extract commit hashes and times."
fi

# input
# 前提是这个 pip3 install pytz，得有这个包  pytz-2020.1-py2.py3-none-any.whl
# sh extractionTime.sh "2024-01-01 09:00:00" "2024-09-30 18:00:00"